package cn.itcast.bos.service.base.impl;

import java.util.List;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.base.SubAreaDao;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.base.SubAreaService;

@Service
@Transactional
public class SubAreaServiceImpl implements SubAreaService {
	
	@Autowired
	private SubAreaDao subAreaDao;
	
	
	public void save(SubArea model) {
		//分区主键类型是String 需要手动指派
		model.setId(UUID.randomUUID().toString());
		subAreaDao.save(model);
	}


	@Override
	public Page<SubArea> pageQuery(Pageable pageable) {
		return subAreaDao.findAll(pageable);
	}


	@Override
	public List<SubArea> findNotAssociation() {
		return subAreaDao.findByFixedAreaNull();
	}


	@Override
	public List<SubArea> findAll() {
		return subAreaDao.findAll();
	}


	@Override
	public List<Object[]> showChart() {
		return subAreaDao.findCountByProvince();
	}
	
	@Override
	public List<SubArea> findHasAssociationByFixedAreaIdsubarea(String id) {
		return subAreaDao.findByFixedAreaId(id);
	}
	@Override
	public Page<SubArea> pageQuery(Pageable pageable, final String fixedAreaId) {
		
		Specification<SubArea> spec = new Specification<SubArea>() {
			
			@Override
			public Predicate toPredicate(Root<SubArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
					Join<Object, Object> join = root.join("fixedArea",JoinType.INNER);
					Predicate p = cb.equal(join.get("id").as(String.class),fixedAreaId);
				return p;
			}
		};
		
		return subAreaDao.findAll(spec, pageable);
	}

	@Override
	public void save(List<SubArea> list) {
		subAreaDao.save(list);
	}

}
